const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const layoutHtml = require('../publicTemp/html')
const fs = require('fs')
const path = require('path')

function makeDir(dir) {
    return new Promise((resolve, reject) => {
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir);
            resolve({
                success: true,
                msg: '成功创建' + dir + '目录'
               
            })
        } else {
            resolve({
                success: false,
                msg: '目录已存在，停止创建'
            })
        }

    })
}
// 创建页面模板目录
function makeTemplate(data) {
    let template = data.template;
    var splitPath = template.split('/');
    let page = path.join(__dirname, '../src/' + splitPath[0] + '/' + splitPath[1]) //src/pages/index
    let components = path.join(__dirname, '../src/' + splitPath[0] + '/' + splitPath[1] + '/components')
    console.log('split---',splitPath);

    var html = splitPath[splitPath.length - 1];
    let htmlTemp = `${page}/${html}`;
    // 创建目录
    makeDir(page).then((res)=>{
        if(res.success){
            // process.stdout(res.msg)
            console.log(res.msg)
        }
    });
    makeDir(components).then(res=>{
        if(res.success){
            // process.stdout(res.msg)
            console.log(res.msg)
        }
    });
    fs.writeFileSync(htmlTemp, layoutHtml(data));
}

//写入json
function writeToPageJson(JsonFile, input, dirname) {
    // 输入的是文件夹名称
    var data = {
        name: dirname,
        title: input,
        template: `pages/${dirname}/${dirname}.html`
    }
    return new Promise((resolve, reject) => {
        const adapter = new FileSync(JsonFile);
        const db = low(adapter)
        db.read().set(data.name, data).write();
        resolve();
    })
}
module.exports = {
    makeDir,
    makeTemplate,
    writeToPageJson
}